package com.tin.triper.UI;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.android.maps.MapView;
import com.tin.triper.Constants;
import com.tin.triper.R;
import com.tin.triper.Data.LocationProvider;
import com.tin.triper.Data.Trip;
import com.tin.triper.Helper.Exporting;
import com.tin.triper.Helper.Formating;
import com.tin.triper.Helper.Importing;
import com.tin.triper.Helper.Utility;
import com.tin.triper.R.id;
import com.tin.triper.R.layout;
import com.tin.triper.R.string;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class TripListActivity extends ListActivity {
	SharedPreferences prefs;
	private TripAdapter adapter;
	private ArrayList<Trip> list = new ArrayList<Trip>();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trip_list);
		prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);
		adapter = new TripAdapter(TripListActivity.this,
				R.layout.trip_list_row, list);
		setListAdapter(adapter);
		loadList();
		getListView().setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				if (list.get(position).tripId == -1) {
					AlertDialog.Builder builder;

					LayoutInflater inflater = (LayoutInflater) TripListActivity.this
							.getSystemService(LAYOUT_INFLATER_SERVICE);
					View layout = inflater.inflate(R.layout.import_trip,
							(ViewGroup) findViewById(R.id.import_trip_layout));

					final EditText fileName = (EditText) layout
							.findViewById(R.id.import_trip_text_field);

					builder = new AlertDialog.Builder(TripListActivity.this);
					builder.setView(layout);
					builder.setPositiveButton(R.string.common_ok,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (!fileName.getText().toString()
											.equals("")) {
										new Importing.ImportTripFromSD(
												TripListActivity.this, fileName
														.getText().toString())
												.execute();
										dialog.dismiss();
									} else {
										Toast.makeText(
												TripListActivity.this,
												getString(R.string.error_message_no_file_name),
												Toast.LENGTH_SHORT).show();
									}
								}
							});
					builder.setNegativeButton(R.string.common_cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
					builder.create().show();

				} else {
					final CharSequence[] items = {
							getString(R.string.trip_list_play),
							getString(R.string.trip_list_export),
							getString(R.string.trip_list_edit_resources),
							getString(R.string.trip_list_erase) };
					AlertDialog.Builder builder = new AlertDialog.Builder(
							TripListActivity.this);
					builder.setItems(items,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int item) {
									if (item == 0) {
										prefs.edit()
												.putInt(Constants.PLAYING_TRIP_ID,
														list.get(position).tripId)
												.commit();
										prefs.edit()
												.putString(
														Constants.PLAYING_TRIP_NAME,
														list.get(position).tripName)
												.commit();
										Intent intent = new Intent(
												TripListActivity.this,
												PlayerActivity.class);
										startActivity(intent);
										finish();
									}
									if (item == 1) {
										final CharSequence[] exportinItems = {
												getString(R.string.export_triper),
												getString(R.string.export_html) };
										AlertDialog.Builder exportingBuilder = new AlertDialog.Builder(
												TripListActivity.this);
										exportingBuilder
												.setTitle(getString(R.string.export_menu));
										exportingBuilder
												.setItems(
														exportinItems,
														new DialogInterface.OnClickListener() {
															public void onClick(
																	DialogInterface dialog,
																	int item) {
																if (item == 0) {
																	new Exporting.ExportTripToSD(
																			TripListActivity.this,
																			list.get(position).tripId,
																			list.get(position).tripName)
																			.execute();
																}
																if (item == 1) {
																	if (Utility
																			.HaveNetworkConnection(TripListActivity.this)) {
																		new ExporitngTask(
																				list.get(position).tripId,
																				0,
																				TripListActivity.this)
																				.execute();
																	} else {
																		Toast.makeText(
																				TripListActivity.this,
																				getString(R.string.export_no_internet_connection),
																				Toast.LENGTH_SHORT)
																				.show();
																	}
																}
															}
														});
										exportingBuilder.create().show();

									}
									if (item == 2) {
										Cursor cursor = getContentResolver()
												.query(LocationProvider.CONTENT_URI_RESOURCES,
														new String[] { LocationProvider.RESOURCE_ID },
														LocationProvider.TRIP_ID
																+ " ='"
																+ list.get(position).tripId
																+ "'", null,
														null);
										if (cursor != null)
											if (cursor.getCount() == 0) {
												Toast.makeText(
														TripListActivity.this,
														getString(R.string.error_message_no_resources),
														Toast.LENGTH_SHORT)
														.show();
												cursor.close();
												return;
											}
										cursor.close();
										Intent intent = new Intent(
												TripListActivity.this,
												ResourcesListActivity.class);
										intent.putExtra(
												Constants.RESOURCE_TRIP_ID,
												list.get(position).tripId);
										intent.putExtra(Constants.TRIP_NAME,
												list.get(position).tripName);
										startActivity(intent);
										finish();
									}
									if (item == 3) {
										getContentResolver()
												.delete(LocationProvider.CONTENT_URI_TRIPS,
														LocationProvider.TRIP_ID
																+ " ='"
																+ list.get(position).tripId
																+ "'", null);
										getContentResolver()
												.delete(LocationProvider.CONTENT_URI_LOCATION,
														LocationProvider.TRIP_ID
																+ " ='"
																+ list.get(position).tripId
																+ "'", null);
										getContentResolver()
												.delete(LocationProvider.CONTENT_URI_RESOURCES,
														LocationProvider.TRIP_ID
																+ " ='"
																+ list.get(position).tripId
																+ "'", null);
										File folder = new File(Environment
												.getExternalStorageDirectory()
												.getAbsolutePath()
												+ "/"
												+ Constants.APP_FOLDER_NAME
												+ list.get(position).tripId
												+ " "
												+ list.get(position).tripName);
										DeleteRecursive(folder);

										loadList();
									}
								}
							});
					builder.create().show();
				}
			}

		});
	}

	void DeleteRecursive(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				File temp = new File(dir, children[i]);
				if (temp.isDirectory()) {
					DeleteRecursive(temp);
				} else {
					boolean b = temp.delete();
				}
			}

			dir.delete();
		}
	}
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if(hasFocus)
			loadList();
	}

	private void loadList() {
		list.clear();
		Cursor cursor = getContentResolver().query(
				LocationProvider.CONTENT_URI_TRIPS,
				new String[] { LocationProvider.TRIP_ID,
						LocationProvider.TRIP_NAME,
						LocationProvider.TRIP_LENGTH,
						LocationProvider.TRIP_TIME }, null, null, null);
		if (cursor != null)
			while (cursor.moveToNext()) {
				Trip trip = new Trip();
				trip.tripId = cursor.getInt(0);
				trip.tripName = cursor.getString(1);
				trip.tripTime = Formating
						.converseToTime(cursor.getInt(3), this);
				trip.tripLength = cursor.getFloat(2) / 1000 + "";
				list.add(trip);
			}
		cursor.close();
		for (int i = 0; i < list.size(); i++) {
			cursor = getContentResolver()
					.query(LocationProvider.CONTENT_URI_LOCATION,
							new String[] { LocationProvider.LOCATION_TIME },
							LocationProvider.TRIP_ID + " ='"
									+ list.get(i).tripId + "'", null,
							LocationProvider.LOCATION_ID);
			if (cursor != null)
				if (cursor.moveToFirst()) {
					list.get(i).date.setTime(cursor.getLong(0));
				}
			cursor.close();
		}
		Trip importTrip = new Trip();
		importTrip.tripName = getString(R.string.trip_list_import);
		importTrip.tripId = -1;
		list.add(importTrip);
		adapter.notifyDataSetChanged();
	}

	private class TripAdapter extends ArrayAdapter<Trip> implements Filterable {

		public ArrayList<Trip> allItems;
		LayoutInflater layoutInflator;

		public TripAdapter(Context context, int textViewResourceId,
				ArrayList<Trip> items) {
			super(context, textViewResourceId, items);
			allItems = items;
		}

		class FeedViewHolder {
			TextView name;
			TextView time;
			TextView distance;
			ImageView check;
			TextView date;
			LinearLayout layout;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			FeedViewHolder feedViewHolder;

			TextView name;
			TextView time;
			TextView date;
			TextView distance;
			ImageView check;
			final Trip o;

			if (allItems.size() != 0)
				o = allItems.get(position);
			else
				o = null;

			if (convertView == null) {
				layoutInflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = layoutInflator.inflate(R.layout.trip_list_row,
						parent, false);
				feedViewHolder = new FeedViewHolder();
				feedViewHolder.name = (TextView) convertView
						.findViewById(R.id.trip_list_trip_name);
				feedViewHolder.time = (TextView) convertView
						.findViewById(R.id.trip_list_time);
				feedViewHolder.distance = (TextView) convertView
						.findViewById(R.id.trip_list_distance);
				feedViewHolder.check = (ImageView) convertView
						.findViewById(R.id.trip_list_rec);
				feedViewHolder.date = (TextView) convertView
						.findViewById(R.id.trip_list_date);

				convertView.setTag(feedViewHolder);
				check = feedViewHolder.check;
				name = feedViewHolder.name;
				distance = feedViewHolder.distance;
				time = feedViewHolder.time;
				date = feedViewHolder.date;
			} else {
				feedViewHolder = (FeedViewHolder) convertView.getTag();
				check = feedViewHolder.check;
				name = feedViewHolder.name;
				distance = feedViewHolder.distance;
				time = feedViewHolder.time;
				date = feedViewHolder.date;
			}
			if (o != null) {
				if (o.tripId == -1) {
					name.setText(o.tripName);
					date.setText("");
					distance.setText("");
					time.setText("");
					check.setVisibility(View.GONE);
				} else {
					name.setText(o.tripName);
					int point = o.tripLength.indexOf('.');
					SimpleDateFormat formatter = new SimpleDateFormat(
							"dd.MM.yy");

					date.setText(getString(R.string.trip_list_date) + ": "
							+ formatter.format(o.date));
					distance.setText(getString(R.string.trip_list_distance)
							+ ": " + o.tripLength.substring(0, point + 2)
							+ " km");
					time.setText(getString(R.string.trip_list_time) + ": "
							+ o.tripTime);

					if (o.tripId == prefs.getInt(Constants.RECORDED_TRIP_ID, 0)
							&& prefs.getBoolean(Constants.IS_RECORDING, false))
						check.setVisibility(View.VISIBLE);
					else
						check.setVisibility(View.GONE);
				}

			}
			convertView.setTag(feedViewHolder);
			return convertView;
		}

	}

	private class ExporitngTask extends AsyncTask<Void, Void, Void> {
		private ProgressDialog dialog;
		private Context context;
		private int tripId;
		private int format;

		public ExporitngTask(int tripId, int format, Context context) {
			this.context = context;
			this.tripId = tripId;
			this.format = format;
			dialog = new ProgressDialog(this.context);
		}

		protected void onPreExecute() {
			dialog.setMessage(getString(R.string.trip_list_exporting));
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}

		protected Void doInBackground(Void... urls) {
			Exporting.exportTripHtml(tripId, context);
			return null;
		}

		protected void onProgressUpdate(Void... progress) {
		}

		protected void onPostExecute(Void result) {
			try {
				if (dialog.isShowing())
					dialog.dismiss();
			} catch (Exception e) {
			}
		}
	}

}
